package com.javaweb.bookstore.filter;

import com.javaweb.bookstore.entity.UserInfo;
import com.javaweb.bookstore.Utils;
import com.javaweb.bookstore.entity.ResponseEntity;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//@WebFilter(urlPatterns = {"/book/*", "/cart/*","/order/*"})
public class AuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //chain pattern链条模式
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession(false);
        if(session == null){
            ResponseEntity re = new ResponseEntity(false, "Please login first!", null);
            String json = Utils.obj2json(re);
            resp.getWriter().println(json);
            return;
        }
        String sid = session.getId();
        UserInfo ui = (UserInfo) session.getAttribute("userinfo");

        if(ui == null) /*没有登陆*/{
            ResponseEntity re = new ResponseEntity(false, "Please login first!", null);
            String json = Utils.obj2json(re);
            resp.getWriter().println(json);
            return;
        }

         filterChain.doFilter(servletRequest, servletResponse);//后续的一串处理都执行了

        //对相应进行后续处理




    }

    @Override
    public void destroy() {

    }
}
